#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "assettreeeditor.h"
#include <QSettings>
#include <QMenu>
#include <QFiledialog>

#include <Core/Core.hpp>
#include <QStandardItemModel>


//////////////////////////////////////////////////////////////////////////
MainWindow::MainWindow( QWidget* parent )
:	QMainWindow( parent )
,	ui( new Ui::MainWindow )
,	mpPackageModel( nullptr )
{
	ui->setupUi(this);
	readSettings();

	// Insert an asset tree editor into the ui.
	ui->AssetsTab->layout()->addWidget( new AssetTreeEditor() );
}


MainWindow::~MainWindow()
{
	delete ui;
}


void MainWindow::logMessage( const std::string& str )
{
	QMutexLocker	lock( &mLock );
	if( ui->LoggingOutput )
	{
		ui->LoggingOutput->append( str.c_str() );
	}
}


void MainWindow::closeEvent( QCloseEvent* event )
{
	writeSettings();
}


void MainWindow::readSettings()
{
	QSettings	settings;

	settings.beginGroup( "MainWindow" );
	restoreGeometry( settings.value( "geometry" ).toByteArray() );
	restoreState( settings.value( "state" ).toByteArray() );

	mWorkingDir.setPath( settings.value( "workingDirectory", QDir::current().path() ).toString() );
	mRecentFiles	=	settings.value( "recentFiles" ).toStringList();

	// TODO: Setup the recent file list.
	if( !mRecentFiles.isEmpty() )
	{
		ui->actionRecent->setEnabled( true );
	}
	else
	{
		ui->actionRecent->setEnabled( false );
	}

	settings.endGroup();
}


void MainWindow::writeSettings()
{
	QSettings	settings;

	settings.beginGroup( "MainWindow" );
	settings.setValue( "geometry", saveGeometry() );
	settings.setValue( "state", saveState() );

	settings.setValue( "workingDirectory", mWorkingDir.path() );
	settings.setValue( "recentFiles", mRecentFiles );
	settings.endGroup();
}


void MainWindow::loadGameConfiguration( const QString& filename )
{
	if( mGameDesc.load( filename ) )
	{
		// Setup the game information panel.
		ui->GameNameInfo->setText( mGameDesc.Name() );
		ui->ProjectFileInfo->setText( mGameDesc.Base() );
	}
}


void MainWindow::saveGameConfiguration( const QString& filename )
{
	mGameDesc.save( filename );
}


void MainWindow::on_actionQuit_triggered()
{
	close();
}


void MainWindow::on_actionCreate_triggered()
{
	mGameDesc.create( this );
}


void MainWindow::on_actionOpen_triggered()
{
	QFileDialog	openFile( this );
	openFile.setNameFilter( "Game Projects(*.gfp)" );
	openFile.setDirectory( mWorkingDir );
	openFile.setAcceptMode( QFileDialog::AcceptOpen );

	if( openFile.exec() )
	{
		// TODO: Close existing.  Save if desired.

		QStringList	files	=	openFile.selectedFiles();
		if( files.size()==1 )
		{
			// Load up the game configuration.
			QString		file	=	files[ 0 ];

			loadGameConfiguration( file );

			// Retain the working directory information.
			mWorkingDir	=	QDir( file );
		}
	}
}

void MainWindow::on_PackageTableRemoveButton_clicked()
{

}


void MainWindow::on_PackageTableAddButton_clicked()
{

}
